﻿using IWshRuntimeLibrary;
using NAudio.CoreAudioApi;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using TroubleshootingofBeanBagAssistant.lCheck;
using TroubleshootingofBeanBagAssistant.ViewModel;
using Brushes = System.Windows.Media.Brushes;
using Path = System.IO.Path;

namespace TroubleshootingofBeanBagAssistant
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : System.Windows.Window
	{
		public MainWindow()
		{
			InitializeComponent();
		}

		[DllImport("user32.dll")]
		[return: MarshalAs(UnmanagedType.Bool)]
		static extern bool IsHungAppWindow(IntPtr hWnd);

		[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
		private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
		private const int MAX_PATH = 260;
		private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;
		public static string GetAllUsersDesktopFolderPath()
		{
			StringBuilder sbPath = new(MAX_PATH);
			SHGetFolderPath(IntPtr.Zero, CSIDL_COMMON_DESKTOPDIRECTORY, IntPtr.Zero, 0, sbPath);
			return sbPath.ToString();
		}


		/// <summary>
		/// 生成快捷方式
		/// </summary>
		public static void UpdateShortcutIco()
		{
			try
			{


				//先删除所有的，重新创建现在的
				RemoveDuplicateShortcutsAll("豆包助手一键疑难解答");


				string initialSource = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), @"豆包助手一键疑难解答.lnk");

				if (!System.IO.File.Exists(initialSource))
				{
					initialSource = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), @"豆包助手一键疑难解答.lnk");
				}

				WshShell shell = new();
				IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(initialSource);//获取快捷方式对象
				string targetPath = shortcut.TargetPath;//读取右键快捷方式的目标信息
				string workingDirectory = shortcut.WorkingDirectory;//读取右键快捷方式的起始位置信息
				int windowStyle = shortcut.WindowStyle;//读取右键快捷方式的运行方式信息
				string description = shortcut.Description;//读取右键快捷方式的备注信息
				string iconLocation = shortcut.IconLocation;//读取 快捷方式的图标信息

				if (!targetPath.Contains("TroubleshootingofBeanBagAssistant"))
				{
					shortcut.TargetPath = System.Windows.Forms.Application.ExecutablePath;
					shortcut.Save();
				}


				//RemoveDuplicateShortcuts("AI办公助手");

				///改名了 去掉之前的
				///
				//RemoveDuplicateShortcutsAll("千寻智能AI助手");

			}
			catch (DllNotFoundException e)
			{
				//LogWriter.Log(e, "DLL not found.");
			}
			catch (EntryPointNotFoundException e)
			{
			}
			catch (BadImageFormatException e)
			{
			}
			catch (Exception e1)
			{
			}




		}


		/// <summary>
		/// 删除相同名称的 lnk 只保留一个
		/// </summary>
		/// <param name="shortcutName"></param>
		/// <returns></returns>
		public static bool RemoveDuplicateShortcutsAll(string shortcutName)
		{

			string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);


			string[] shortcutPaths = Directory.GetFiles(desktopPath, $"{shortcutName}.lnk", SearchOption.TopDirectoryOnly);

			string desktopPathPublic = "C:\\Users\\Public\\Desktop";
			string[] shortcutPathsPublic = Directory.GetFiles(desktopPathPublic, $"{shortcutName}.lnk", SearchOption.TopDirectoryOnly);

			if (shortcutPaths.Length > 0)
			{
				foreach (string path in shortcutPaths)
				{
					try
					{
						System.IO.File.Delete(path);
						//Debug.WriteLine($"Deleted duplicate shortcut: {path}");
					}
					catch (Exception)
					{
						//Debug.WriteLine($"Failed to delete shortcut {path}: {ex.Message}");
					}
				}
				return true; // 成功删除了至少一个
			}

			else if (shortcutPathsPublic.Length > 0)
			{
				foreach (string path in shortcutPathsPublic)
				{
					try
					{
						System.IO.File.Delete(path);
						//Debug.WriteLine($"Deleted duplicate shortcut: {path}");
					}
					catch (Exception)
					{
						//Debug.WriteLine($"Failed to delete shortcut {path}: {ex.Message}");
					}
				}
				return true; // 成功删除了至少一个
			}
			else
			{
				//Debug.WriteLine($"No duplicate shortcuts found with name '{shortcutName}'.lnk");
				return false;
			}
		}



		private void RepeatButton_Click(object sender, RoutedEventArgs e)
		{
			LoadingCircle.Visibility = Visibility.Visible;
			TagTextBlock.Text = "检查任务执行中...";
			TagTextBlock.Foreground = Brushes.Black;

			// 开始前先清空代办
			ViewModelLocator.ListViewViewModel.DelDataList();

			_ = Task.Run(() =>
			{
				try
				{
					// 1. 构建所有检查项
					var checks = new List<IDiagnosticCheck>
						{
							new ProcessStatusCheck(),
							new DesktopShortcutMethodCheck(),
							new AllowAppstoAccessYourMicrophoneCheck(),
							new HidMouseDeviceCheck(),
							new NetworkCheck(),           // 新增：本地网络检测
							new PingCheck(),              // 新增：外部主机Ping检测
							new AudioEndPointsCheck(),    // 新增：麦克风设备检测
							new ErrorLogsCheck(),         // 新增：错误日志检测
							new FirewallCheck(),
							new LicenseCheck(),
							new DiskSpaceCheck(),
							new AntivirusCheck(),
							// 其他检查项...
						};

					// 2. 依次执行并收集结果
					foreach (var check in checks)
					{
						var result = check.Run();
						Utils.UIBeginInvoke(() => AddResult(result.Title, result.Detail));
					}

					RestartBeanBagAI();

					Utils.UIBeginInvoke(() =>
					{
						AddResult("所有检查任务已完成", "请查看结果列表");
						// 保存和复制结果到剪贴板的逻辑...
						// 1. 获取ListView数据
						var dataList = ViewModelLocator.ListViewViewModel.DataList;
						if (dataList != null && dataList.Count > 0)
						{
							// 2. 格式化为文本
							var sb = new StringBuilder();
							sb.AppendLine("问题名称\t是否解决\t时间");
							foreach (var item in dataList)
							{
								sb.AppendLine($"{item.Index}\t{item.Remark}\t{item.Timeofappearance}");
							}
							string resultText = sb.ToString();

							// 3. 保存为文本文档
							string filePath = Path.Combine(
								Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
								$"豆包助手疑难解答_{DateTime.Now:yyyyMMdd_HHmmss}.txt");
							System.IO.File.WriteAllText(filePath, resultText, Encoding.UTF8);

							// 4. 复制到剪贴板
							System.Windows.Clipboard.SetText(resultText);

							// 5. 可选：提示用户
							AddResult("检查结果已保存并复制到剪贴板", $"文件路径: {filePath}");
						}
						else
						{
							AddResult("无检查结果可保存", "");
						}

					});



				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				finally
				{
					Utils.UIBeginInvoke(() =>
					{
						TagTextBlock.Text = "已解决";
						TagTextBlock.Foreground = Brushes.Green;
						okBtn.Visibility = Visibility.Visible;
						LoadingCircle.Visibility = Visibility.Collapsed;
					});
				}
			});


		}

		// 辅助方法：添加检查结果到列表
		void AddResult(string index, string remark)
		{
			var app = new ListViewDataModel
			{
				Index = index,
				Timeofappearance = DateTime.Now.ToString(),
				Remark = remark
			};
			ViewModelLocator.ListViewViewModel.AddDataList(app);
		}



		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			LoadingCircle.Visibility = Visibility.Collapsed;
			okBtn.Visibility = Visibility.Collapsed;
			//UpdateShortcutIco();

		}

		// 创建快捷方式到桌面的方法
		public static void CreateShortcutOnDesktop(string shortcutName, string targetPath)
		{
			string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			string shortcutPath = System.IO.Path.Combine(desktopPath, shortcutName + ".lnk");

			WshShell shell = new();
			IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
			shortcut.TargetPath = targetPath;
			shortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(targetPath);
			shortcut.WindowStyle = 1;
			shortcut.Description = shortcutName;
			shortcut.IconLocation = targetPath;
			shortcut.Save();
		}

		public static void KillAllBeanBagAIProcesses()
		{
			string processName = "AIMouse"; // 不带.exe
			var processes = Process.GetProcessesByName(processName);
			foreach (var process in processes)
			{
				try
				{
					process.Kill();
				}
				catch (Exception ex)
				{
					// 可根据需要记录或处理异常
					Console.WriteLine($"关闭进程失败: {ex.Message}");
				}
			}
		}


		public static void RestartBeanBagAI()
		{
			// 1. 关闭所有进程
			KillAllBeanBagAIProcesses();

			// 2. 检查桌面快捷方式
			string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			string shortcutPath = System.IO.Path.Combine(desktopPath, "AIMouse.lnk");
			string exePath = @"C:\Users\Administrator\AppData\Local\Programs\BeanBagAIBrowserEdge\Applications\AIMouse.exe";

			try
			{
				if (System.IO.File.Exists(shortcutPath))
				{
					// 启动快捷方式
					Process.Start(new ProcessStartInfo
					{
						FileName = shortcutPath,
						UseShellExecute = true
					});
				}
				else
				{
					// 启动主程序
					Process.Start(new ProcessStartInfo
					{
						FileName = exePath,
						UseShellExecute = true
					});
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine($"启动失败: {ex.Message}");
			}
		}

		private void loadbtn_Click(object sender, RoutedEventArgs e)
		{
			RestartBeanBagAI();

		}

		public IEnumerable<MMDevice> CaptureDevices { get; set; }


		/// <summary>
		/// 查询麦克风是否匹配，并进行UI提示
		/// </summary>
		public void EnumerateAudioEndPoints()
		{
			try
			{
				MMDeviceEnumerator enumerator = new();
				var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, NAudio.CoreAudioApi.DeviceState.Active).ToArray();
				CaptureDevices = devices;

				if (devices.Length == 0)
				{
					Utils.UIBeginInvoke(() =>
					{
						AddResult("未检测到可用麦克风设备", "请检查麦克风是否插好或已启用");
					});
					return;
				}

				MMDevice defaultDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Console);

				bool foundAIMic = false;
				foreach (MMDevice device in devices)
				{
					if (device.DeviceFriendlyName.ToLower() == "unknown")
						continue;

					int result = GetIdByName(device.DeviceFriendlyName);

					// 检查系统默认麦克风
					if (device.DeviceFriendlyName == defaultDevice.DeviceFriendlyName)
					{
						if (result == 0)
						{
							foundAIMic = true;
							Utils.UIBeginInvoke(() =>
							{
								AddResult("系统默认麦克风为AI设备", $"当前设备: {device.DeviceFriendlyName}");
							});
						}
						else
						{
							Utils.UIBeginInvoke(() =>
							{
								AddResult("系统默认麦克风不是AI设备", $"当前设备: {device.DeviceFriendlyName}");
							});
						}
					}
				}

				// 如果没有任何AI设备
				if (!foundAIMic)
				{
					bool hasAIMic = devices.Any(d => GetIdByName(d.DeviceFriendlyName) == 0);
					if (hasAIMic)
					{
						Utils.UIBeginInvoke(() =>
						{
							AddResult("检测到AI麦克风，但未设为默认", "请在系统声音设置中将AI麦克风设为默认");
						});
					}
					else
					{
						Utils.UIBeginInvoke(() =>
						{
							AddResult("未检测到AI麦克风", "请检查AI麦克风是否已正确连接");
						});
					}
				}
			}
			catch (Exception ex)
			{
				Utils.UIBeginInvoke(() =>
				{
					AddResult("麦克风检测异常", ex.Message);
				});
			}
		}

		/// <summary>
		/// 麦克风名称匹配
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public int GetIdByName(string name)
		{
			int ManufacturerID = -1;
			try
			{

				if (name.Contains("AiMouse"))
				{
					ManufacturerID = 0;
				}

			}
			catch (Exception ex)
			{

				//LogWriter.Log("麦克风名称匹配 MyDevice GetIdByName ", ex.Message);
			}
			return ManufacturerID;

		}

		/// <summary>
		/// 检查是否存在错误日志
		/// </summary>
		private void CheckErrorLogs()
		{

			string logDir = @"C:\Users\Administrator\AppData\Local\Programs\BeanBagAIBrowserEdge\Applications\BeanBagAI\LogsError";

			try
			{
				if (Directory.Exists(logDir))
				{
					var files = Directory.GetFiles(logDir, "*.*", SearchOption.TopDirectoryOnly);
					if (files.Length > 0)
					{
						Utils.UIBeginInvoke(() =>
						{
							AddResult("检测到应用运行异常，存在错误日志", $"日志文件数: {files.Length}");
						});
					}
					else
					{
						Utils.UIBeginInvoke(() =>
						{
							AddResult("未检测到错误日志", "应用运行正常");
						});
					}
				}
				else
				{
					Utils.UIBeginInvoke(() =>
					{
						AddResult("未检测到错误日志目录", "应用运行正常");
					});
				}
			}
			catch (Exception ex)
			{
				Utils.UIBeginInvoke(() =>
				{
					AddResult("检查错误日志时发生异常", ex.Message);
				});
			}
		}

		/// <summary>
		/// 检查是否有防火墙规则限制AIMouse
		/// </summary>
		private void CheckFirewallRules()
		{
			try
			{
				// 获取当前程序路径或指定目标程序路径
				string exePath = @"C:\Users\Administrator\AppData\Local\Programs\BeanBagAIBrowserEdge\Applications\AIMouse.exe";
				// 你也可以用 System.Windows.Forms.Application.ExecutablePath

				// 使用netsh命令查询防火墙规则
				ProcessStartInfo psi = new ProcessStartInfo
				{
					FileName = "netsh",
					Arguments = $"advfirewall firewall show rule name=all | find /I \"{Path.GetFileName(exePath)}\"",
					RedirectStandardOutput = true,
					UseShellExecute = false,
					CreateNoWindow = true
				};
				using var process = Process.Start(psi);
				string output = process.StandardOutput.ReadToEnd();

				process.WaitForExit();

				if (!string.IsNullOrWhiteSpace(output))
				{
					Utils.UIBeginInvoke(() =>
					{
						AddResult("检测到防火墙规则可能限制软件使用", $"相关规则: {output.Trim()}");
					});
				}
				else
				{
					Utils.UIBeginInvoke(() =>
					{
						AddResult("未检测到防火墙限制本软件的规则", "防火墙未发现限制规则");
					});
				}
			}
			catch (Exception ex)
			{
				Utils.UIBeginInvoke(() =>
				{
					AddResult("防火墙规则检查异常", ex.Message);
				});
			}
		}

		/// <summary>
		/// 检查证书/许可证有效性（截止到2026-05-29）
		/// </summary>
		private void CheckLicenseValidity()
		{
			DateTime expireDate = new DateTime(2026, 5, 29);
			DateTime now = DateTime.Now;
			if (now > expireDate)
			{
				Utils.UIBeginInvoke(() =>
				{
					AddResult("证书/许可证已过期", $"当前时间: {now:yyyy-MM-dd}，到期时间: {expireDate:yyyy-MM-dd}");
				});
			}
			else
			{
				Utils.UIBeginInvoke(() =>
				{
					AddResult("证书/许可证有效", $"当前时间: {now:yyyy-MM-dd}，到期时间: {expireDate:yyyy-MM-dd}");
				});
			}
		}

		private void MoreBtn_Click(object sender, RoutedEventArgs e)
		{

			//if (WindowsAPPBorder.Visibility == Visibility.Visible)
			//{
			//	WindowsAPPBorder.Visibility = Visibility.Collapsed;
			//}
			//else
			//{
			//	WindowsAPPBorder.Visibility = Visibility.Visible;
			//}
		}

		private void clearBtn_Click(object sender, RoutedEventArgs e)
		{

		}

		private void OpenLogs_Click(object sender, RoutedEventArgs e)
		{

		}

		private void Checkforupdates_Click(object sender, RoutedEventArgs e)
		{

		}
		private void ResetMicrophonePermission_Click(object sender, RoutedEventArgs e)
		{
			Task.Run(() =>
			{
				string resultMsg = "";
				string detailMsg = "";
				try
				{
					// 获取当前程序目录
					string currentDir = AppDomain.CurrentDomain.BaseDirectory;

					// 返回上一级目录
					string parentDir = Directory.GetParent(currentDir)?.FullName;
					if (string.IsNullOrEmpty(parentDir))
					{
						resultMsg = "无法获取上级目录";
						detailMsg = "请检查程序运行路径";
					}
					else
					{
						// WebView2.UDF 文件夹路径
						string udfDir = Path.Combine(parentDir, "WebView2.UDF");
						udfDir=udfDir.Replace(@"\TroubleshootingofBeanBagAssistant", "");
						if (Directory.Exists(udfDir))
						{
							Directory.Delete(udfDir, true);
							resultMsg = "已重置麦克风权限";
							detailMsg = "WebView2.UDF 文件夹已成功删除";
						}
						else
						{
							resultMsg = $"未找到 WebView2.UDF 文件夹";
							detailMsg = "无需重置，文件夹不存在";
						}
					}
				}
				catch (Exception ex)
				{
					resultMsg = "重置麦克风权限失败";
					detailMsg = ex.Message;
				}

				// UI线程展示结果
				Utils.UIBeginInvoke(() =>
				{
					AddResult(resultMsg, detailMsg);
					// 可选：弹窗提示
					HandyControl.Controls.MessageBox.Show(resultMsg + "\n" + detailMsg, "操作结果", MessageBoxButton.OK, MessageBoxImage.Information);
				});
			});
		}


	}
}